package com.zhaoxi.project.hrp.controller;

import com.zhaoxi.common.utils.SecurityUtils;
import com.zhaoxi.common.utils.StringUtils;
import com.zhaoxi.common.utils.poi.ExcelUtil;
import com.zhaoxi.framework.aspectj.lang.annotation.Log;
import com.zhaoxi.framework.aspectj.lang.enums.BusinessType;
import com.zhaoxi.framework.web.BaseService;
import com.zhaoxi.framework.web.PageData;
import com.zhaoxi.framework.web.page.TableDataInfo;
import com.zhaoxi.project.hrp.domain.HrpPartner;
import com.zhaoxi.project.hrp.domain.SysDept;
import com.zhaoxi.project.hrp.domain.SysRole;
import com.zhaoxi.project.hrp.domain.SysUser;
import com.zhaoxi.project.hrp.service.SysDeptServiceImpl;
import com.zhaoxi.project.hrp.service.SysRoleServiceImpl;
import com.zhaoxi.project.hrp.service.UserService;
import com.zhaoxi.project.hrp.service.impl.HrpPartnerServiceImpl;
import com.zhaoxi.project.hrp.service.impl.HrpPostServiceImpl;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author zhaoxi
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends BaseService {
  @Autowired
  private UserService userService;

  @Autowired
  private SysRoleServiceImpl roleService;

  @Autowired
  private SysDeptServiceImpl deptService;

  @Autowired
  private HrpPostServiceImpl postService;

  @Autowired
  private HrpPartnerServiceImpl hrpPartnerService;




//  2024年2月6日, PM 12:09:10
  //============之前的暂时不关联，以后慢慢改吧======================


  /**
   * 获取用户列表
   */
  @PreAuthorize("@ss.hasPermi('sys:user:list')")
  @GetMapping("/list")
  public TableDataInfo list(SysUser user) {
    startPage();
    List<SysUser> list = userService.selectUserList(user);
    return getDataTable(list);
  }

  @Log(title = "用户管理", businessType = BusinessType.EXPORT)
  @PreAuthorize("@ss.hasPermi('sys:user:export')")
  @PostMapping("/export")
  public void export(HttpServletResponse response, SysUser user) {
    List<SysUser> list = userService.selectUserList(user);
    ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
    util.exportExcel(response, list, "用户数据");
  }

  @Log(title = "用户管理", businessType = BusinessType.IMPORT)
  @PreAuthorize("@ss.hasPermi('sys:user:import')")
  @PostMapping("/importData")
  public PageData importData(MultipartFile file, boolean updateSupport) throws Exception {
    ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
    List<SysUser> userList = util.importExcel(file.getInputStream());
    String operName = getUsername();
    String message = userService.importUser(userList, updateSupport, operName);
    return success(message);
  }

  @PostMapping("/importTemplate")
  public void importTemplate(HttpServletResponse response) {
    ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
    util.importTemplateExcel(response, "用户数据");
  }

  /**
   * 根据用户编号获取详细信息
   */
  @PreAuthorize("@ss.hasPermi('sys:user:query')")
  @GetMapping(value = {"/", "/{userId}"})
  public PageData getInfo(@PathVariable(value = "userId", required = false) Long userId) {
    userService.checkUserDataScope(userId);
    PageData ajax = PageData.success();
    List<SysRole> roles = roleService.selectRoleAll();
    ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
    ajax.put("posts", postService.selectPostAll());
    if (StringUtils.isNotNull(userId)) {
      SysUser sysUser = userService.selectUserById(userId);
      sysUser.setPassword(null);// 将根据用户id查询到的用户密码手动置空，不必在新增/修改用户对话框中显示
      ajax.put("data", sysUser);
      ajax.put("postIds", postService.selectPostListByUserId(userId));
      ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
    }
    return ajax;
  }

  /**
   * 新增用户
   */
  @PreAuthorize("@ss.hasPermi('sys:user:add')")
  @Log(title = "用户管理", businessType = BusinessType.INSERT)
  @PostMapping
  public PageData add(@Validated @RequestBody SysUser user) {
    if (!userService.checkUserNameUnique(user)) {
      return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
    } else if (StringUtils.isNotEmpty(user.getMobile()) && !userService.checkPhoneUnique(user)) {
      return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
    } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
      return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
    }
    // 对新增用户时对合作伙伴表中的（手机号码，邮箱，性别）等字段中不可修改的用户信息校验
    HrpPartner hrpPartner = hrpPartnerService.selectHrpPartnerById(user.getUserId());
    String str1 = new String();
    String str2 = new String();
    str1 = hrpPartner.getMobile() + hrpPartner.getEmail() + hrpPartner.getSex();
    str2 = user.getMobile() + user.getEmail() + user.getSex();
    if(!str1.equals(str2)) {
      return error("新增用户'" + user.getUserName() + "'失败，（手机号码，邮箱，性别）不允许修改");
    }
    // 如果当前新增用户是之前被删除（del_flag == "2"）的用户，则将之前被标记的删除用户彻底删除
    SysUser sysUser = userService.selectUserById(user.getUserId());
    if(sysUser != null && sysUser.getDelFlag().equals("2")) {
      userService.completeDeleteUserById(sysUser.getUserId());
    }
    return toAjax(userService.insertUser(user));
  }

  /**
   * 修改用户
   */
  @PreAuthorize("@ss.hasPermi('sys:user:edit')")
  @Log(title = "用户管理", businessType = BusinessType.UPDATE)
  @PutMapping
  public PageData edit(@Validated @RequestBody SysUser user) {
    userService.checkUserAllowed(user);
    userService.checkUserDataScope(user.getUserId());
    if (!userService.checkUserNameUnique(user)) {
      return error("修改用户'" + user.getLoginName() + "'失败，登录账号已存在");
    } else if (StringUtils.isNotEmpty(user.getMobile()) && !userService.checkPhoneUnique(user)) {
      return error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
    } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
      return error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
    }
    // 对修改用户信息时对合作伙伴表中的（手机号码，邮箱，性别）等字段中不可修改的用户信息校验
    HrpPartner hrpPartner = hrpPartnerService.selectHrpPartnerById(user.getUserId());
    String str1 = new String();
    String str2 = new String();
    str1 = hrpPartner.getMobile() + hrpPartner.getEmail() + hrpPartner.getSex();
    str2 = user.getMobile() + user.getEmail() + user.getSex();
    if (!str1.equals(str2)) {
      return error("修改用户'" + user.getLoginName() + "'失败，（手机号码，邮箱，性别）不允许修改");
    }
    user.setUpdateBy(getUsername());
    return toAjax(userService.updateUser(user));
  }

  /**
   * 删除用户
   */
  @PreAuthorize("@ss.hasPermi('sys:user:remove')")
  @Log(title = "用户管理", businessType = BusinessType.DELETE)
  @DeleteMapping("/{userIds}")
  public PageData remove(@PathVariable Long[] userIds) {
    if (ArrayUtils.contains(userIds, getUserId())) {
      return error("当前用户不能删除");
    }
    return toAjax(userService.deleteUserByIds(userIds));
  }

  /**
   * 重置密码
   */
  @PreAuthorize("@ss.hasPermi('sys:user:resetPwd')")
  @Log(title = "用户管理", businessType = BusinessType.UPDATE)
  @PutMapping("/resetPwd")
  public PageData resetPwd(@RequestBody SysUser user) {
    userService.checkUserAllowed(user);
    userService.checkUserDataScope(user.getUserId());
    user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
    user.setUpdateBy(getUsername());
    return toAjax(userService.resetPwd(user));
  }

  /**
   * 状态修改
   */
  @PreAuthorize("@ss.hasPermi('sys:user:edit')")
  @Log(title = "用户管理", businessType = BusinessType.UPDATE)
  @PutMapping("/changeStatus")
  public PageData changeStatus(@RequestBody SysUser user) {
    userService.checkUserAllowed(user);
    userService.checkUserDataScope(user.getUserId());
    user.setUpdateBy(getUsername());
    return toAjax(userService.updateUserStatus(user));
  }

  /**
   * 根据用户编号获取授权角色
   */
  @PreAuthorize("@ss.hasPermi('sys:user:query')")
  @GetMapping("/authRole/{userId}")
  public PageData authRole(@PathVariable("userId") Long userId) {
    PageData ajax = PageData.success();
    SysUser user = userService.selectUserById(userId);
    List<SysRole> roles = roleService.selectRolesByUserId(userId);
    ajax.put("user", user);
    ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
    return ajax;
  }

  /**
   * 用户授权角色
   */
  @PreAuthorize("@ss.hasPermi('sys:user:edit')")
  @Log(title = "用户管理", businessType = BusinessType.GRANT)
  @PutMapping("/authRole")
  public PageData insertAuthRole(Long userId, Long[] roleIds) {
    userService.checkUserDataScope(userId);
    userService.insertUserAuth(userId, roleIds);
    return success();
  }

  /**
   * 获取部门树列表
   */
  @PreAuthorize("@ss.hasPermi('sys:user:list')")
  @GetMapping("/deptTree")
  public PageData deptTree(SysDept dept) {
    return success(deptService.selectDeptTreeList(dept));
  }
}
